<?php
/* Author: ThanhTV
 * Email: thanhtran@vietnambiz.com
 * Date create: 21/12/2010
 * Description: User model
 */
class user_model extends MY_Model{
	
	var $table = 'tbl_users';
	var $role = 'tbl_aclroles';
	
	function user_model(){
		parent::MY_Model();
		$this->load->library('session');
		$this->set_table($this->table);
		$this->set_id('id');
		session_start();
	}
	
	function login($user = '',$pass = ''){
		if($user == '' || $pass == ''){
			return false;
		}
		$where = array(
			'user'	=>	$user,
			'pass'	=>	md5($pass)
		);
		$this->db->select()
				 ->from($this->table)
				 ->join($this->role,$this->role.'.id='.$this->table.'.roleid')
				 ->where($where);
		//$this->set_where($where);
		$q = $this->db->get();
		$row = $q->row();
		//print_r($where);
		if($row){
			$_SESSION["login"]["user"]     = $row->user;
			$_SESSION["login"]["pass"]     = $row->pass;
			$_SESSION["login"]["id"]       = $row->userid;
			$_SESSION["login"]["roleid"]   = $row->roleid;			
                        $_SESSION["login"]["role"]     = isset($row->role);
                        
			return true;
		}
		return false;
	}
	
	function check_login(){
		//$user = $this->session->userdata('user');
		if(isset($_SESSION["login"])){
			
			$user = $_SESSION["login"]["user"];
			$pass = $_SESSION["login"]["pass"];
			$where = array(
                            'user'	=>	$user,
                            'pass'	=>	$pass
			);
			$this->db->select()
					 ->from($this->table)
					 ->join($this->role,$this->role.'.id='.$this->table.'.roleid')
					 ->where($where);
			//$this->set_where($where);
			$q = $this->db->get();
			$row = $q->row();
			//print_r($where);
			if($row){
				$_SESSION["login"]["user"]     = $row->user;
				$_SESSION["login"]["pass"]     = $row->pass;
				$_SESSION["login"]["id"]       = $row->userid;
				$_SESSION["login"]["roleid"]   = $row->roleid;
				return true;
			}
			
		}
		return false;
	}
	
	function logout(){
		 session_destroy();
	}
   
	function get_user_info($id=0)
	{
    	
    	$query = $this->db->where('userid', $id)->get('tbl_users');
        
        if($query->num_rows() > 0) {
            $data = $query->row();
        }

        return $data;
    }
    function get_all_users()
    {

        $rs = $this->db->where("userid !=",1)->get('tbl_users')->result();
        //$rs = $this->db->get('tbl_users')->result();
        return $rs;
    }

    function get_count_all_user($active="")
    {
        $this->db->select("count(userid) as m")->from('tbl_users');
	      if(!empty($active)){
	      	$this->db->where("status",$active);
	      }
          $rs = $this->db->get()->row();
          return $rs->m;
    }

    function del_user($id)
    {
        		
    	$query = $this->db->where('userid', $id)->get('tbl_users');
        
        if($query->num_rows() > 0) {
            return $this->db->where('userid', $id)->delete('tbl_users');
        }
        return false;
    	
    }
}